<script setup lang="ts">
import { defineEmits, onMounted, ref } from 'vue';
import type { FormInst, FormItemRule, FormRules } from 'naive-ui';
import { useDialog } from 'naive-ui';
import { getIndustryList, insertFolder, msgCheckAction } from '@/service/api';
import { localStg } from '@/utils/storage';

interface Props {
  folderData?: any[];
}

const props = withDefaults(defineProps<Props>(), {
  folderData: () => []
});

const showModal = ref(false);

const emit = defineEmits(['update-value', 'refresh']);

/** 创建自定义错误信息的必填表单规则 */
const createRequiredFormRule = (message = '不能为空'): FormItemRule => ({
  required: true,
  message
});

const typeOptions = ref([]);

const formRef = ref<HTMLElement & FormInst>();

interface FormData {
  parentId: number;
  folderName: string;
  businessIndustry: string;
  businessType: number;
  status: number;
}

const formData = ref<FormData>({
  parentId: 0, // 父级id
  folderName: '', // 文件名称
  businessIndustry: '1', // 行业类型
  businessType: 1,
  status: 0 // 终端（1：机顶盒 2：小程序）
});

// 校验规则
const rules: FormRules = {
  folderName: {
    required: true,
    message: '请输入',
    trigger: 'blur'
  },
  businessIndustry: createRequiredFormRule('请选择'),
  businessType: createRequiredFormRule('请选择')
};

function buildNewFolder(): any {
  showModal.value = true;
  formData.value.folderName = '';
}

function handleJumpFolder(item: any): any {
  emit('update-value', 2, item);
}

// 查询文件列表
async function getIndustryOptions() {
  const { data, error } = await getIndustryList();
  if (!error) {
    typeOptions.value = data;
  }
}

const dialog = useDialog();

// 新增文件夹提交
async function handleSubmit() {
  await formRef.value?.validate(async errors => {
    if (!errors) {
      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: formData.value.folderName
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `公司名称中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const { data, error } = await insertFolder(formData.value);
      if (!error) {
        showModal.value = false;
        window.$message?.success('新增成功!');
        emit('refresh', 0);
      }
    }
  });
}
// 初始化
onMounted(() => {
  getIndustryOptions();
});
</script>

<template>
  <div class="w-full">
    <div class="files">
      <div class="uploadFile file">
        <img class="typeImg" src="@/assets/bid-materials/folder-trans.png" alt="" />
        <div class="fileName">
          <NButton
            color="#FFFFFF"
            text-color="#333333"
            strong
            style="width: 220px; font-size: 16px"
            @click="buildNewFolder"
          >
            新建文件夹
          </NButton>
        </div>
      </div>
      <div v-for="item in folderData" class="file" @click="handleJumpFolder(item)">
        <img class="typeImg" src="@/assets/bid-materials/folder.png" alt="" />
        <div class="fileName">{{ item.folderName }}</div>
      </div>
    </div>
  </div>
  <NModal v-model:show="showModal">
    <NCard
      header-style="font-size: 32px;colo: '#333333'"
      footer-style="text-align:center"
      style="width: 1080px; border-radius: 30px"
      title="新建公司文件夹"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
      closable
      @close="
        () => {
          showModal = false;
        }
      "
    >
      <template #header-extra></template>
      <span style="color: #4501b7; font-size: 20px">公司文件夹用于搭建贵司知识库</span>
      <NForm
        ref="formRef"
        label-placement="left"
        label-width="100"
        size="large"
        style="margin-top: 30px"
        :model="formData"
        :rules="rules"
      >
        <NFormItem label="公司名称" required path="folderName">
          <NInput v-model:value="formData.folderName" placeholder="请输入" />
        </NFormItem>
        <NFormItem label="公司行业" required path="businessIndustry">
          <NSelect
            v-model:value="formData.businessIndustry"
            :options="typeOptions"
            label-field="dictLabel"
            value-field="dictValue"
            placeholder="请选择"
          />
        </NFormItem>
        <NFormItem label="与我司关系" required path="businessType">
          <NRadioGroup v-model:value="formData.businessType" name="businessType">
            <NSpace>
              <NRadio :value="1">合作伙伴</NRadio>
              <NRadio :value="2">集团公司</NRadio>
            </NSpace>
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NButton secondary type="primary" size="large" @click="handleSubmit">+ 新建</NButton>
      </template>
    </NCard>
  </NModal>
</template>

<style scoped lang="scss">
.files {
  padding-top: 20px;
  width: 1583px;
  height: 650px;
  display: flex;
  flex-wrap: wrap;
  .file {
    width: 281px;
    height: 180px;
    border-radius: 12px;
    border: 1px solid #ebeef5;
    margin: 16px 16px;
    position: relative;
    &:hover {
      background: #f3f4f8;
      cursor: pointer;
    }
    .typeImg {
      position: absolute;
      top: 44px;
      left: 106px;
      width: 70px;
      height: 59px;
    }
    .fileName {
      text-align: center;
      width: 281px;
      padding: 0 30px;
      margin-top: 120px;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      line-clamp: 1; /* 这里的3表示最多显示2行 */
      overflow: hidden;
    }
  }
}
.uploadFile {
  background: #f3f4f8;
}
</style>
